<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>HTML5 WebSocket / Geolocation 追踪器</title>
		<link rel="stylesheet" href="styles.css">
	</head>
	<body onload="loadDemo()">

		<h1>HTML5 WebSocket / Geolocation 追踪器</h1>

		<div><strong>Geolocation</strong>: <p id="geoStatus">你的浏览器不支持HTML5 Geolocation</p></div>
		<div><strong>WebSocket</strong>: <p id="socketStatus">你的浏览器不支持HTML5 Web Sockets</p></div>


	</body>
	<script>
		//WebSocket的引用
		var ws;
		//为该会话生成的唯一随机的ID
		var myId = Math.floor(100000*Math.random());
		//当前显示的行数
		var rowCount;
		
		function updateSocketStatus(message){
			document.getElementById("socketStatus").innerHTML = message;
		}
		
		function updateGeolocationStatus(message){
			document.getElementById("geoStatus").innerHTML = message;
		}
		
		function loadDemo(){
			//确保浏览器支持WebSocket
			if(window.WebSocket){
				url = "ws://localhost:8080";//broadcast WebSocket服务器位置
				ws = new WebSocket(url);
				
				ws.onopen = function(){
					updateSocketStatus("连接已建立");
				}
				
				ws.onmessage = function(e){
					updateSocketStatus("更新位置数据：" + dataReturned(e.data));
				}
			}
		}
		
		var geo;
		if(navigator.geolocation){
			geo = navigator.geolocation;
			updateGeolocationStatus("浏览器支持HTML5 Geolocation");
		}

		geo.watchPosition(updateLocation,handleLocationError,{maximumAge:20000});//每20s更新一次

		function updateLocation(position){
			var latitude = position.coords.latitude;
			var longitude = position.coords.longitude;
			var timestamp = position.timestamp;
			
			updateGeolocationStatus("位置更新时间：" + timestamp);
			
			var toSend = JSON.stringify([myId,latitude,longitude]);
			sendMyLocation(toSend);
		}
		
		function sendMyLocation(newLocation){
			if(ws){
				ws.send(newLocation)
			}
		}
		
		function dataReturned(locationData){
			var allData = JSON.parse(locationData);
			var incomingId = allData[1];
			var incomingLat = allData[2];
			var incomingLong = allData[3];
			var incomingRow = document.getElementById(incomingId);
			if(!incomingRow){
				incomingRow = document.getElementById("div");
				incomingRow.setAttribute("id",incomingId);
				
				incomingRow.userText = (incomingId == myId)?"Me":'User' + rowCount;
				rowCount++;
				document.body.appendChild(incomingRow);
				
			}
			
			incomingRow.innerHTML = incomingRow.userText + " \\ Lat: " +
                                incomingLat + " \\ Lon: " +
                                incomingLong;

			return incomingRow.userText;
		}
		
		function handleLocationError(error){
			switch(error.code){
				case 0:
				  updateGeolocationStatus("检索位置信息出错: " + error.message);
				  break;
				case 1:
				  updateGeolocationStatus("用户阻止获取位置信息。");
				  break;
				case 2:
				  updateGeolocationStatus("浏览器不能检测你的位置信息: " + error.message);
				  break;
				case 3:
				  updateGeolocationStatus("浏览器检索位置信息超时。");
				  break;
			}
		}
	</script>
</html>
